using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using GonzalesCore.CoreElements;
using GonzalesCore.CoreManagers;
using Kypris2.CoreElements;
using Kypris2.Utils;
using Jamila2.Tools;

public partial class GonzalesReportGeneralClaimants : System.Web.UI.Page
{
    #region Variables

    protected PrivateLoginSession CurrentPrivateSession = null;
    protected LogManager CurLogManager = null;
    protected DataView ResultView = null;

    #region ResultTable
    protected DataTable ResultTable
    {
        get
        {
            return (DataTable)ViewState["ResultTable"];
        }

        set
        {
            ViewState["ResultTable"] = value;
        }
    }
    #endregion

    #region UnexpectedError
    protected string UnexpectedError
    {
        get
        {
            return ViewState["UnexpectedError"].ToString();
        }

        set
        {
            ViewState["UnexpectedError"] = value;
        }
    }
    #endregion

    #region Download
    protected string Download
    {
        get
        {
            return ViewState["Download"].ToString();
        }

        set
        {
            ViewState["Download"] = value;
        }
    }
    #endregion

    #region GridViewHeader
    protected ArrayList GridViewHeader
    {
        get
        {
            return (ArrayList)ViewState["GridViewHeader"];
        }

        set
        {
            ViewState["GridViewHeader"] = value;
        }
    }
    #endregion

    #endregion

    #region Events

    protected void Page_Load(object sender, EventArgs e)
    {
        this.SessionCheck();

        this.Table_MessageBox.Visible = false;  // always default to false
        this.HyperLink_FileDownload.Visible = false;

        if (!IsPostBack)
        {
            this.PageComponentSetup();
            this.SwitchLanguage();
        }

    }
    protected void Button_Submit_Click(object sender, EventArgs e)
    {
        if (this.DropDownList_ByCompany.SelectedIndex > 0)
        {
            this.LoadData();

            if (this.ResultTable != null)
            {
                //DataView ResultView = new DataView(this.ResultTable);
                this.BindData(this.ResultView);
            }
        }
    }

    protected void DropDownList_ByEntity_SelectedIndexChanged(object sender, EventArgs e)
    {
        using (CompanyManager CurCompanyManager = new CompanyManager(this.CurrentPrivateSession))
        {
            GonzalesCompanies ResultList = CurCompanyManager.GetCompanyByEntityID(this.DropDownList_ByEntity.SelectedValue);

            if (ResultList != null)
            {
                this.DropDownList_ByCompany.Items.Clear();
                this.DropDownList_ByCompany.Items.Add(new ListItem("", ""));

                for (int x = 0; x < ResultList.Count; x++)
                {
                    this.DropDownList_ByCompany.Items.Add(new ListItem(ResultList[x].CompanyName, ResultList[x].InternalID));
                }
            }
            else
            {
                this.CurLogManager.LogError("[GonzalesReportGeneralClaimants.DropDownList_ByEntity_SelectedIndexChanged] : Failed on CurCompanyManager.GetCompanyByEntityID('" + this.DropDownList_ByEntity.SelectedValue + "') : " + CurCompanyManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
            }
        }

        #region Filter the company by Finance Admin
        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsFinanceAdmin)
        {
            using (UserManager CurUserManager = new UserManager(this.CurrentPrivateSession))
            {
                GonzalesCompanies ResultCompanies = CurUserManager.GetCompanyByFinanceAdmin(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);
                if (ResultCompanies != null)
                {
                    int x = 1;

                    while (x < this.DropDownList_ByCompany.Items.Count)
                    {
                        bool Matched = false;

                        for (int y = 0; y < ResultCompanies.Count; y++)
                        {
                            if (ResultCompanies[y].InternalID.CompareTo(this.DropDownList_ByCompany.Items[x].Value) == 0)
                            {
                                Matched = true;
                                break;
                            }
                        }

                        if (!Matched)
                        {
                            this.DropDownList_ByCompany.Items.RemoveAt(x);
                        }
                        else
                        {
                            x++;
                        }
                    }
                }
            }
        }
        #endregion
    }

    protected void Button_CSV_Click(object sender, EventArgs e)
    {
        this.Button_Submit_Click(sender, e);

        if (this.ResultTable != null)
        {
            string FileName = "Report-Claimants-" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString() + DateTime.Now.Day.ToString() + DateTime.Now.Hour.ToString() + DateTime.Now.Minute.ToString() + ".csv";
            string ErrorMessage = "";

            if (!ReportsGenerator.GenerateCSV(this.ResultView.ToTable(), Server.MapPath("ReportsOutput") + "\\" + FileName, ref ErrorMessage))
            {
                string LogID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(LogID, "[GonzalesReportGeneralClaimants.Button_CSV_Click] : Failed at ReportsGenerator.GenerateCSV : " + ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage(this.UnexpectedError + LogID);
            }
            else
            {
                this.HyperLink_FileDownload.Text = this.Download + FileName;
                this.HyperLink_FileDownload.NavigateUrl = "ReportsOutput/" + FileName;
                this.HyperLink_FileDownload.Visible = true;                
            }
        }
    }

    #region OnRowCreated
    protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.Header)
        {
            TableCellCollection cells = e.Row.Cells;

            for (int i = 0; i < this.GridViewHeader.Count; i++)
            {
                cells[i].Text = this.GridViewHeader[i].ToString();
            }
        }
    }
    #endregion

    #endregion

    #region Customized Methods

    #region SessionCheck
    public void SessionCheck()
    {

        if (Session[GonzalesCommonNamingConvention.CurrentPrivateSession] != null)
        {
            this.CurrentPrivateSession = (PrivateLoginSession)Session[GonzalesCommonNamingConvention.CurrentPrivateSession];
            this.CurLogManager = new LogManager(this.CurrentPrivateSession);    // activate Log Manager
        }
        else
        {
            Response.Redirect(GonzalesErrorPageRedirect.SessionError);
        }

    }
    #endregion

    #region PageComponentSetup
    protected void PageComponentSetup()
    {
        // setup entity
        if (this.CurrentPrivateSession.CurrentLoggedOnUser.IsPowerAdmin)
        {
            #region Power Admin
            using (EntityManager CurEntityManager = new EntityManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection ResultList = CurEntityManager.GetAllEntity();
                if (ResultList != null)
                {
                    this.DropDownList_ByEntity.Items.Add(new ListItem("", ""));
                    for (int x = 0; x < ResultList.Count; x++)
                    {
                        this.DropDownList_ByEntity.Items.Add(new ListItem(ResultList[x].DisplayName, ResultList[x].InternalID));
                    }
                }
                else
                {
                    // display error
                    this.CurLogManager.LogError("[GonzalesAdminClaimantsListing.PageComponentSetup] : Failed on CurEntityManager.GetAllEntity() : " + CurEntityManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);

                }
            }
            #endregion
        }
        else
        {
            #region Finance Admin

            using (UserManager CurManager = new UserManager(this.CurrentPrivateSession))
            {
                MasterBaseCollection ResultList = CurManager.GetEntityByFinanceAdmin(this.CurrentPrivateSession.CurrentLoggedOnUser.InternalID);
                if (ResultList != null)
                {
                    for (int x = 0; x < ResultList.Count; x++)
                    {
                        this.DropDownList_ByEntity.Items.Add(new ListItem(ResultList[x].DisplayName, ResultList[x].InternalID));
                    }
                }
                else
                {
                    // display error
                    this.CurLogManager.LogError("[GonzalesAdminClaimantsListing.PageComponentSetup] : Failed on CurEntityManager.GetAllEntity() : " + CurManager.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                }
            }

            #endregion
        }

        this.DropDownList_ByEntity_SelectedIndexChanged(null, null);
    }
    #endregion

    #region SwitchLanguage
    protected void SwitchLanguage()
    {
        try
        {
            using (MultiLingualFactory CurLanguageFactory = MultiLingualEngine.GetMultiLingualFactory(this, this.CurrentPrivateSession.CurrentLoggedOnUser.PreferedLanguage.InternalID))
            {
                this.Label_ADName.Text = CurLanguageFactory.DisplayValue("ADName");
                this.Label_ApprRoute.Text = CurLanguageFactory.DisplayValue("ApprRoute");
                this.Label_Company.Text = CurLanguageFactory.DisplayValue("Company");
                this.Label_CostCenter.Text = CurLanguageFactory.DisplayValue("CostCenter");
                this.Label_EmployeeID.Text = CurLanguageFactory.DisplayValue("EmployeeID");
                this.Label_Entity.Text = CurLanguageFactory.DisplayValue("Entity");
                this.Label_HavingStopPoint.Text = CurLanguageFactory.DisplayValue("HavingStopPoint");
                this.Label_Information.Text = CurLanguageFactory.DisplayValue("Information");
                this.Label_Name.Text = CurLanguageFactory.DisplayValue("Name");
                this.Label_PageTitle.Text = CurLanguageFactory.DisplayValue("PageTitle");
                this.Label_Sorting.Text = CurLanguageFactory.DisplayValue("Sorting");
                this.Button_CSV.Text = CurLanguageFactory.DisplayValue("CSV");
                this.Button_Submit.Text = CurLanguageFactory.DisplayValue("Submit");
                this.UnexpectedError = CurLanguageFactory.DisplayValue("UnexpectedError");
                this.Download = CurLanguageFactory.DisplayValue("Download");

                this.GridViewHeader = new ArrayList();
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("EmployeeID2"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("ActiveDirectoryID"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("DisplayName"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("CostCenter2"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("ApprovingCurrency"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("ApprovingLimit"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("StopFlag"));
                this.GridViewHeader.Add(CurLanguageFactory.DisplayValue("ApprovingRouting"));

                // approvel route
                this.DropDownList_ApprRouting.Items.Add(new ListItem("", ""));
                this.DropDownList_ApprRouting.Items.Add(new ListItem(ClaimManager.GetApprovingRoute(ApprovingRoute.Normal), ClaimManager.GetApprovingRouteInCode(ApprovingRoute.Normal).ToString()));
                this.DropDownList_ApprRouting.Items.Add(new ListItem(ClaimManager.GetApprovingRoute(ApprovingRoute.MultiLevel), ClaimManager.GetApprovingRouteInCode(ApprovingRoute.MultiLevel).ToString()));
                this.DropDownList_ApprRouting.Items.Add(new ListItem(ClaimManager.GetApprovingRoute(ApprovingRoute.Exception), ClaimManager.GetApprovingRouteInCode(ApprovingRoute.Exception).ToString()));

                // stop point
                this.DropDownList_HavingStopPoint.Items.Add(new ListItem("", "%"));
                this.DropDownList_HavingStopPoint.Items.Add(new ListItem("Yes", "Yes"));
                this.DropDownList_HavingStopPoint.Items.Add(new ListItem("No", ""));

                // sort by
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("EmployeeID2"), "EmployeeID"));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ActiveDirectoryID"), "ActiveDirectoryID"));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("DisplayName"), "DisplayName"));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("CostCenter2"), "CostCenter"));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ApprovingCurrency"), "ApprovingCurrency"));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ApprovingLimit"), "ApprovingLimit"));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("StopFlag"), "StopFlag"));
                this.DropDownList_SortBy.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ApprovingRouting"), "ApprovingRouting"));

                this.DropDownList_SortOrder.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("ASC"), "ASC"));
                this.DropDownList_SortOrder.Items.Add(new ListItem(CurLanguageFactory.DisplayValue("DESC"), "DESC"));
            }
        }
        catch (Exception ex)
        {
            this.CurLogManager.LogError("[GonzalesReportGeneralClaimants.SwitchLanguage.EX] : " + ex.Message, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.User);
        }

    }
    #endregion

    #region ShowErrorMessage
    protected void ShowErrorMessage(string ErrorMessage)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = ErrorMessage;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "ErrorBox";
    }
    #endregion

    #region ShowMessage
    protected void ShowMessage(string Message)
    {
        this.Table_MessageBox.Visible = true;
        this.Table_MessageBox.Rows[0].Cells[0].Text = Message;
        this.Table_MessageBox.Rows[0].Cells[0].CssClass = "MessageBox";
    }
    #endregion

    #endregion

    #region Data Operation

    #region LoadData
    protected void LoadData()
    {
        using (ReportsGenerator CurReportGenerator = new ReportsGenerator(this.CurrentPrivateSession))
        {
            if ((this.ResultTable = CurReportGenerator.GetClaimantReportsByCompany(this.DropDownList_ByCompany.SelectedValue)) != null)
            {
                this.ResultView = new DataView(this.ResultTable);

                // filter
                StringBuilder FilterBuilder = new StringBuilder();

                if (this.TextBox_ADName.Text.Trim().Length > 0)
                {
                    FilterBuilder.Append(((FilterBuilder.Length > 0) ? " AND " : "") + "ActiveDirectoryID = '" + this.TextBox_ADName.Text + "'");
                }

                if (this.TextBox_DisplayName.Text.Trim().Length > 0)
                {
                    FilterBuilder.Append(((FilterBuilder.Length > 0) ? " AND " : "") + "DisplayName LIKE '%" + this.TextBox_DisplayName.Text + "%'");
                }

                if (this.DropDownList_ApprRouting.SelectedIndex > 0)
                {
                    FilterBuilder.Append(((FilterBuilder.Length > 0) ? " AND " : "") + "ApprovingRouting = '" + this.DropDownList_ApprRouting.SelectedItem.Text + "'");
                }

                if (this.TextBox_EmployeeID.Text.Trim().Length > 0)
                {
                    FilterBuilder.Append(((FilterBuilder.Length > 0) ? " AND " : "") + "EmployeeID = '" + this.TextBox_EmployeeID.Text + "'");
                }

                if (this.TextBox_CostCenter.Text.Trim().Length > 0)
                {
                    FilterBuilder.Append(((FilterBuilder.Length > 0) ? " AND " : "") + "CostCenter = '" + this.TextBox_CostCenter.Text + "'");
                }

                if (this.DropDownList_HavingStopPoint.SelectedIndex > 0)
                {
                    FilterBuilder.Append(((FilterBuilder.Length > 0) ? " AND " : "") + "StopFlag = '" + this.DropDownList_HavingStopPoint.SelectedValue + "'");
                }                

                this.ResultView.RowFilter = FilterBuilder.ToString();
                this.ResultView.Sort = this.DropDownList_SortBy.SelectedValue + " " + this.DropDownList_SortOrder.SelectedValue;
                
                
            }
            else
            {
                string LogID = SwissArmy.UniqueID();
                this.CurLogManager.LogError(LogID, "[GonzalesReportGeneralClaimants.LoadData] : Failed at CurReportGenerator.GetClaimantReportsByCompany('" + this.DropDownList_ByCompany.SelectedValue + "') : " + CurReportGenerator.ErrorMessage, this.CurrentPrivateSession.CurrentLoggedOnUser, LogInterface.System);
                this.ShowErrorMessage(this.UnexpectedError + LogID);
            }
        }
    }

    #endregion

    #region BindData

    private void BindData(DataView result)
    {
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    private void BindData(DataView result, int pageindex)
    {
        this.GridViewResult.PageIndex = pageindex;
        this.GridViewResult.DataSource = result;
        this.GridViewResult.DataBind();
    }

    #endregion

    #endregion
}
